import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class RegisterFrame extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JPasswordField confirmPasswordField;
    private JTextField realNameField;
    private JTextField emailField;
    private JTextField phoneField;
    private JComboBox<String> roleComboBox;
    private JButton registerButton;
    private JButton cancelButton;
    private UserDAO userDAO;

    public RegisterFrame() {
        userDAO = new UserDAO();
        initComponents();
        setupLayout();
        setupEvents();
    }

    private void initComponents() {
        setTitle("用户注册");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setSize(600, 500);
        setLocationRelativeTo(null);
        setResizable(false);

        // 创建输入框
        usernameField = new JTextField();
        usernameField.setFont(new Font("微软雅黑", Font.PLAIN, 16));

        passwordField = new JPasswordField();
        passwordField.setFont(new Font("微软雅黑", Font.PLAIN, 16));

        confirmPasswordField = new JPasswordField();
        confirmPasswordField.setFont(new Font("微软雅黑", Font.PLAIN, 16));

        realNameField = new JTextField();
        realNameField.setFont(new Font("微软雅黑", Font.PLAIN, 16));

        emailField = new JTextField();
        emailField.setFont(new Font("微软雅黑", Font.PLAIN, 16));

        phoneField = new JTextField();
        phoneField.setFont(new Font("微软雅黑", Font.PLAIN, 16));

        // 角色选择
        String[] roles = { "student", "teacher" };
        roleComboBox = new JComboBox<>(roles);
        roleComboBox.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        roleComboBox.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected,
                    boolean cellHasFocus) {
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                if (value.equals("student")) {
                    setText("学生");
                } else if (value.equals("teacher")) {
                    setText("教师");
                }
                return this;
            }
        });

        // 按钮
        registerButton = new JButton("注册");
        registerButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
        registerButton.setBackground(new Color(40, 167, 69));
        registerButton.setForeground(Color.WHITE);
        registerButton.setBorder(BorderFactory.createEmptyBorder(12, 0, 12, 0));
        registerButton.setFocusPainted(false);
        registerButton.setCursor(new Cursor(Cursor.HAND_CURSOR));

        cancelButton = new JButton("取消");
        cancelButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
        cancelButton.setBackground(new Color(108, 117, 125));
        cancelButton.setForeground(Color.WHITE);
        cancelButton.setBorder(BorderFactory.createEmptyBorder(12, 0, 12, 0));
        cancelButton.setFocusPainted(false);
        cancelButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
    }

    private void setupLayout() {
        setLayout(new BorderLayout());
        getContentPane().setBackground(Color.WHITE);

        // 主面板
        JPanel mainPanel = new JPanel();
        mainPanel.setBackground(Color.WHITE);
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(30, 40, 30, 40));

        // 标题
        JLabel titleLabel = new JLabel("用户注册", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 26));
        titleLabel.setForeground(new Color(51, 51, 51));
        titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

        // 表单面板 - 使用GridBagLayout实现两列布局
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBackground(Color.WHITE);
        formPanel.setBorder(BorderFactory.createEmptyBorder(25, 0, 0, 0));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(8, 10, 8, 10);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 第一行：用户名 和 真实姓名
        addFormRow(formPanel, gbc, 0, "用户名", usernameField, "真实姓名", realNameField);

        // 第二行：密码 和 确认密码
        addFormRow(formPanel, gbc, 1, "密码", passwordField, "确认密码", confirmPasswordField);

        // 第三行：邮箱 和 手机号
        addFormRow(formPanel, gbc, 2, "邮箱", emailField, "手机号", phoneField);

        // 第四行：角色（居中，占两列）
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.EAST;
        gbc.fill = GridBagConstraints.NONE;
        JLabel roleLabel = createLabel("角色");
        formPanel.add(roleLabel, gbc);

        gbc.gridx = 1;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        styleField(roleComboBox, 240);
        formPanel.add(roleComboBox, gbc);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 0));
        buttonPanel.setBackground(Color.WHITE);
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(25, 0, 0, 0));

        registerButton.setPreferredSize(new Dimension(120, 40));
        cancelButton.setPreferredSize(new Dimension(120, 40));

        buttonPanel.add(registerButton);
        buttonPanel.add(cancelButton);

        // 添加组件到主面板
        mainPanel.add(titleLabel);
        mainPanel.add(formPanel);
        mainPanel.add(buttonPanel);

        add(mainPanel, BorderLayout.CENTER);
    }

    private void addFormRow(JPanel parent, GridBagConstraints gbc, int row,
            String label1Text, JComponent field1,
            String label2Text, JComponent field2) {

        // 左侧标签
        gbc.gridx = 0;
        gbc.gridy = row * 2; // 每行占用两个网格行（标签行和字段行）
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.NONE;
        JLabel leftLabel = createLabel(label1Text);
        parent.add(leftLabel, gbc);

        // 右侧标签
        gbc.gridx = 1;
        JLabel rightLabel = createLabel(label2Text);
        parent.add(rightLabel, gbc);

        // 左侧字段
        gbc.gridx = 0;
        gbc.gridy = row * 2 + 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        styleField(field1, 240);
        parent.add(field1, gbc);

        // 右侧字段
        gbc.gridx = 1;
        styleField(field2, 240);
        parent.add(field2, gbc);
    }

    private JLabel createLabel(String text) {
        JLabel label = new JLabel(text);
        label.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        label.setForeground(new Color(102, 102, 102));
        return label;
    }

    private void styleField(JComponent field, int width) {
        field.setPreferredSize(new Dimension(width, 35));
        field.setBackground(new Color(248, 249, 250));

        if (field instanceof JTextField || field instanceof JPasswordField) {
            field.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                    BorderFactory.createEmptyBorder(8, 12, 8, 12)));
        } else if (field instanceof JComboBox) {
            field.setBorder(BorderFactory.createLineBorder(new Color(220, 220, 220), 1));
        }
    }

    private void setupEvents() {
        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                register();
            }
        });

        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
    }

    private void register() {
        String username = usernameField.getText().trim();
        String password = new String(passwordField.getPassword());
        String confirmPassword = new String(confirmPasswordField.getPassword());
        String realName = realNameField.getText().trim();
        String email = emailField.getText().trim();
        String phone = phoneField.getText().trim();
        String role = (String) roleComboBox.getSelectedItem();

        if (username.isEmpty() || password.isEmpty() || realName.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请填写必填项（用户名、密码、真实姓名）！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        if (!password.equals(confirmPassword)) {
            JOptionPane.showMessageDialog(this, "两次输入的密码不一致！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        if (password.length() < 6) {
            JOptionPane.showMessageDialog(this, "密码长度不能少于6位！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setRealName(realName);
        user.setEmail(email);
        user.setPhone(phone);
        user.setRole(role);

        if (userDAO.register(user)) {
            JOptionPane.showMessageDialog(this, "注册成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
            dispose();
        } else {
            JOptionPane.showMessageDialog(this, "注册失败！用户名可能已存在。", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}